<?php
/**
 * Created by PhpStorm.
 * User: xuewl
 * Date: 2018/1/3
 * Time: 17:20
 */

namespace app\goods\controller\admin;

use app\admin\controller\Backend;

class GoodsStock extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('goods/goods_stock', 'service');
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $result = $this->model->create($params);
            if (!$result) {
                return $this->error($this->model->getError());
            } else {
                return $this->success('success');
            }
        } else {
            return $this->view->fetch();
        }
    }


    /**
     * 卡密导入
     */
    public function import()
    {
        $row = $this->model->find($this->request->param('id', 0));
        if (!$row) {
            return $this->error('不存在');
        }

        if (request()->isPost()) {
            vendor("phpoffice.phpexcel.Classes.PHPExcel");
            vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
            $excel = request()->file('excel')->getInfo();
            $objPHPExcel = \PHPExcel_IOFactory::load($excel['tmp_name']);//读取上传的文件
            $tickets = $objPHPExcel->getSheet(0)->toArray();//获取其中的数据

            $info = [];
            foreach ($tickets as $key => $ticket) {
                if ($key == 0) continue;
                $info[] = [
                    'stock_id' => $row['id'],
                    'content'  => implode(",", $ticket)
                ];
            }
            $result = model('goods/goods_stock_ticket')->saveAll($info);
            if(!$result) {
                return $this->error(model('goods/goods_stock_ticket')->getError());
            } else {
                return $this->success('操作成功');
            }

        }
        return $this->view
            ->assign('row', $row)
            ->fetch();
    }

}
